import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { getUserDesigns, deleteDesign, Design } from '../services/design';
import DesignPreview from '../components/DesignPreview';

const ProfileDesigns: React.FC = () => {
  const [designs, setDesigns] = useState<Design[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedDesign, setSelectedDesign] = useState<Design | null>(null);
  const { user } = useAuth();
  const history = useHistory();

  useEffect(() => {
    if (user) {
      loadDesigns();
    } else {
      setLoading(false);
    }
  }, [user]);

  const loadDesigns = async () => {
    try {
      setLoading(true);
      const response = await getUserDesigns();
      if (response.success) {
        setDesigns(response.data.designs);
      } else {
        setError(response.message || 'Failed to load designs');
      }
    } catch (err) {
      setError('Failed to load designs');
      console.error('Error loading designs:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteDesign = async (id: string) => {
    if (!window.confirm('Are you sure you want to delete this design?')) {
      return;
    }

    try {
      const response = await deleteDesign(id);
      if (response.success) {
        setDesigns(designs.filter(design => design.id !== id));
        if (selectedDesign?.id === id) {
          setSelectedDesign(null);
        }
      } else {
        setError('Failed to delete design');
      }
    } catch (err) {
      setError('Failed to delete design');
      console.error('Error deleting design:', err);
    }
  };

  const handleCreateDesign = () => {
    history.push('/design');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'text-green-600 bg-green-100';
      case 'processing':
        return 'text-yellow-600 bg-yellow-100';
      case 'failed':
        return 'text-red-600 bg-red-100';
      default:
        return 'text-gray-600 bg-gray-100';
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">Please log in to view your designs</h2>
          <p className="text-gray-600">You need to be logged in to access your designs.</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading your designs...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">My Designs</h1>
          <p className="text-xl text-gray-600">View and manage your AI-generated room designs</p>
        </div>

        {/* Error Display */}
        {error && (
          <div className="max-w-4xl mx-auto mb-8">
            <div className="bg-red-50 border border-red-200 rounded-lg p-4">
              <div className="flex items-center">
                <svg className="w-5 h-5 text-red-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
                <p className="text-red-800">{error}</p>
              </div>
              <div className="mt-3">
                <button
                  onClick={loadDesigns}
                  className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 transition-colors"
                >
                  Try Again
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Create Design Button */}
        <div className="max-w-7xl mx-auto mb-8">
          <button
            onClick={handleCreateDesign}
            className="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors"
          >
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Create New Design
          </button>
        </div>

        {designs.length === 0 ? (
          <div className="text-center py-12 bg-white rounded-2xl shadow-xl max-w-4xl mx-auto">
            <div className="text-gray-400 mb-4">
              <svg className="mx-auto h-24 w-24" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
            <h3 className="text-lg font-medium text-gray-900 mb-2">No designs yet</h3>
            <p className="text-gray-600 mb-6">Start creating your first AI-generated room design!</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {designs.map((design) => (
              <motion.div
                key={design.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5 }}
                className="bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow cursor-pointer"
                onClick={() => setSelectedDesign(design)}
              >
                <div className="aspect-w-16 aspect-h-9 bg-gray-200">
                  {design.generatedImageUrl ? (
                    <img
                      src={design.generatedImageUrl}
                      alt={`${design.designStyle} ${design.roomType} design`}
                      className="w-full h-48 object-cover"
                    />
                  ) : (
                    <div className="w-full h-48 bg-gray-200 flex items-center justify-center">
                      <span className="text-gray-400">No image available</span>
                    </div>
                  )}
                </div>
                <div className="p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(design.status)}`}>
                      {design.status ? design.status.charAt(0).toUpperCase() + design.status.slice(1) : 'Unknown'}
                    </span>
                    <span className="text-sm text-gray-500">{design.creditsUsed} credit{design.creditsUsed !== 1 ? 's' : ''}</span>
                  </div>
                  <h3 className="font-semibold text-gray-900 mb-1">
                    {design.designStyle ? design.designStyle.charAt(0).toUpperCase() + design.designStyle.slice(1) : 'Unknown'} {design.roomType ? design.roomType.charAt(0).toUpperCase() + design.roomType.slice(1) : 'Room'}
                  </h3>
                  <p className="text-sm text-gray-600 mb-2 line-clamp-2">{design.prompt}</p>
                  <p className="text-xs text-gray-500">{formatDate(design.createdAt)}</p>
                  {design.errorMessage && (
                    <p className="text-xs text-red-600 mt-1">{design.errorMessage}</p>
                  )}
                </div>
              </motion.div>
            ))}
          </div>
        )}

        {/* Design Detail Modal */}
        {selectedDesign && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
              <div className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-2xl font-bold text-gray-900">
                    {selectedDesign.designStyle ? selectedDesign.designStyle.charAt(0).toUpperCase() + selectedDesign.designStyle.slice(1) : 'Unknown'} {selectedDesign.roomType ? selectedDesign.roomType.charAt(0).toUpperCase() + selectedDesign.roomType.slice(1) : 'Room'}
                  </h2>
                  <button
                    onClick={() => setSelectedDesign(null)}
                    className="text-gray-400 hover:text-gray-600 transition-colors"
                  >
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    {selectedDesign.generatedImageUrl ? (
                      <img
                        src={selectedDesign.generatedImageUrl}
                        alt={`${selectedDesign.designStyle} ${selectedDesign.roomType} design`}
                        className="w-full rounded-lg shadow-md"
                      />
                    ) : (
                      <div className="w-full h-64 bg-gray-200 flex items-center justify-center rounded-lg">
                        <span className="text-gray-400">No image available</span>
                      </div>
                    )}
                  </div>

                  <div>
                    <div className="space-y-4">
                      <div>
                        <h3 className="text-sm font-medium text-gray-500">Status</h3>
                        <p className={`mt-1 ${getStatusColor(selectedDesign.status).split(' ')[0]}`}>
                          {selectedDesign.status ? selectedDesign.status.charAt(0).toUpperCase() + selectedDesign.status.slice(1) : 'Unknown'}
                        </p>
                      </div>

                      <div>
                        <h3 className="text-sm font-medium text-gray-500">Room Type</h3>
                        <p className="mt-1 text-gray-900">{selectedDesign.roomType ? selectedDesign.roomType.charAt(0).toUpperCase() + selectedDesign.roomType.slice(1) : 'Unknown'}</p>
                      </div>

                      <div>
                        <h3 className="text-sm font-medium text-gray-500">Design Style</h3>
                        <p className="mt-1 text-gray-900">{selectedDesign.designStyle ? selectedDesign.designStyle.charAt(0).toUpperCase() + selectedDesign.designStyle.slice(1) : 'Unknown'}</p>
                      </div>

                      <div>
                        <h3 className="text-sm font-medium text-gray-500">Prompt</h3>
                        <p className="mt-1 text-gray-900">{selectedDesign.prompt}</p>
                      </div>

                      <div>
                        <h3 className="text-sm font-medium text-gray-500">Created</h3>
                        <p className="mt-1 text-gray-900">{formatDate(selectedDesign.createdAt)}</p>
                      </div>

                      <div>
                        <h3 className="text-sm font-medium text-gray-500">Credits Used</h3>
                        <p className="mt-1 text-gray-900">{selectedDesign.creditsUsed}</p>
                      </div>

                      {selectedDesign.errorMessage && (
                        <div>
                          <h3 className="text-sm font-medium text-red-500">Error</h3>
                          <p className="mt-1 text-red-600">{selectedDesign.errorMessage}</p>
                        </div>
                      )}
                    </div>

                    <div className="mt-6 flex space-x-4">
                      {selectedDesign.generatedImageUrl && (
                        <a
                          href={selectedDesign.generatedImageUrl}
                          download={`design-${selectedDesign.id}.jpg`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors"
                        >
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                          </svg>
                          Download
                        </a>
                      )}

                      <button
                        onClick={() => handleDeleteDesign(selectedDesign.id)}
                        className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-red-600 bg-white hover:bg-red-50 transition-colors"
                      >
                        <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                        Delete
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ProfileDesigns;